using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using OrbitOne.GoogleCustomSearch.QueryParameters;

namespace OrbitOne.GoogleCustomSearch
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:GoogleCustomSearchControl runat=server></{0}:GoogleCustomSearchControl>")]
    public class GoogleCustomSearchControl : System.Web.UI.WebControls.WebControl,INamingContainer
    {
        #region Members
        private GoogleCustomSearch _customSearch = new GoogleCustomSearch();
        private string _searchResultXsltTemplatePath;
        private string _userInterfaceLanguage="en";
        private string _searchResultLanguage="lang_en";
        private string _searchButtonText = "Search";


        #region GUI Members
        private Label _labelSearch = new Label();
        private TextBox _textBoxSearch = new TextBox();
        private Button _buttonSearch = new Button();
        private Panel _normalSearchPanel = new Panel();
        private Panel _resultPanel = new Panel();
        private HtmlGenericControl _divResultContainer = new HtmlGenericControl("div");
		
        #endregion GUI Members
        #endregion Members
        #region Properties

        [Bindable(true),Category("Appearance"),DefaultValue(""),Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }

        [Bindable(true),Category("Appearance"),DefaultValue(""),Localizable(true)]
        public string LabelSearchText
        {
            get
            {
                return _labelSearch.Text;
            }

            set
            {
                _labelSearch.Text = value;
            }
        }


      
        [Bindable(true),Category("Misc"),DefaultValue(""),Localizable(true)]
        public string SearchResultXsltTemplatePath
        {
            get
            {
                return _searchResultXsltTemplatePath;
            }

            set
            {
                _searchResultXsltTemplatePath = value;
            }
        }



        [Bindable(true),DefaultValue("en"),Category("Misc"),Localizable(true)]
        [Description("The interface language (host language) of your user interface. Value is a two-letter country code: fr, en, nl...")]
        public string UserInterfaceLanguage
        {
            get
            {
               
                return _userInterfaceLanguage;
            }

            set
            {
                _userInterfaceLanguage = value;
               
            }
        }


        [Bindable(true),DefaultValue("lang_en"),Category("Misc"),Localizable(true)]
        [Description("Language restricts search results to documents written in a particular language. For example: lang_en, lang_fr...")]
        public string SearchResultLanguage
        {
            get
            {
                return _searchResultLanguage;
            }

            set
            {
                _searchResultLanguage = value;
               
                
            }
        }


        [Bindable(true),Category("Appearance"),DefaultValue("Search"),Localizable(true)]
        public string SearchButtonText
        {
            get
            {
                return _searchButtonText;
            }

            set
            {
                _searchButtonText = value;
             
            }
        }


		[Bindable(true),Category("Appearance"),Localizable(true)]
		public string SearchButtonCss
		{
			get
			{
				return _buttonSearch.CssClass;
			}

			set
			{
				_buttonSearch.CssClass = value;
             
			}
		}

		[Bindable(true),Category("Appearance"),Localizable(true)]
		public string TextBoxSearchCss
		{
			get
			{
				return _textBoxSearch.CssClass;
			}

			set
			{
				_textBoxSearch.CssClass = value;
             
			}
		}

		[Bindable(true),Category("Appearance"),Localizable(true)]
		public string LabelSearchCss
		{
			get
			{
				return _labelSearch.CssClass;
			}

			set
			{
				_labelSearch.CssClass = value;
             
			}
		}









        #endregion Properties

        #region Event Handler
        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(Text);
            if (_customSearch.ParameterBuilder.CanSearch)
            {
                _divResultContainer.InnerHtml = _customSearch.TransformResultToHtml(Page.Server.MapPath(_searchResultXsltTemplatePath));
            }
            RegisterTextBoxSearchEnterKey();
            _normalSearchPanel.RenderControl(output);
          
            _resultPanel.RenderControl(output);
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            InitializeButtonSearch();
            _labelSearch.ID = "_labelSearch";
            _textBoxSearch.ID = "_textBoxSearch";
            _normalSearchPanel.DefaultButton = _buttonSearch.ID;
            _normalSearchPanel.Controls.Add(_labelSearch);
			_normalSearchPanel.Controls.Add(CreateSeparator("&nbsp;"));
            _normalSearchPanel.Controls.Add(_textBoxSearch);
			_normalSearchPanel.Controls.Add(CreateSeparator("&nbsp;"));
            _normalSearchPanel.Controls.Add(_buttonSearch);

          
            _resultPanel.Controls.Add(_divResultContainer); 
            Controls.Add(_normalSearchPanel);
            Controls.Add(_resultPanel);
        }

        protected void ButtonSearch_Click(object sender, EventArgs e)
        {
            QueryParameters.Q query = new QueryParameters.Q();
            query.Value = _textBoxSearch.Text;
           _customSearch.ParameterBuilder.Add(query);
          
            HL hl = new HL();
            hl.Value = UserInterfaceLanguage;
           _customSearch.ParameterBuilder.Add(hl);
           
            LR lr = new LR();
           lr.Value = SearchResultLanguage;
           _customSearch.ParameterBuilder.Add(lr);
			//To avoid browser generate page expired info, do a page redirect
			Page.Response.Redirect(Page.Request.Url.GetLeftPart(UriPartial.Path)+this._customSearch.ParameterBuilder.Build());
          

       }


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            
            foreach(string str in this.Page.Request.QueryString.AllKeys)
            {
                QueryParameters.QueryParameter parameter = QueryParameters.QueryParameterFactory.Create(str);
                if (parameter != null)
                {
                    parameter.Value = this.Page.Request.QueryString[str];
                    this._customSearch.ParameterBuilder.Add(parameter);
					if(parameter.GetType() == typeof(QueryParameters.Q))
					{
						this._textBoxSearch.Text = parameter.Value;
					}
                }
            }
        }

       


        #endregion Event Handler



       #region Methods
        public GoogleCustomSearchControl() : base(HtmlTextWriterTag.Div) { }
        private void InitializeButtonSearch()
        {
            _buttonSearch.ID = "_buttonSearch";
            _buttonSearch.Text = SearchButtonText;
            _buttonSearch.Click += new EventHandler(ButtonSearch_Click);

        }
        private void RegisterTextBoxSearchEnterKey()
        {
            _textBoxSearch.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + _buttonSearch.ClientID + "').click();return false;}} else {return true}; ");
        }
		private HtmlGenericControl CreateSeparator(string separator)
		{
			HtmlGenericControl control  = new HtmlGenericControl();
			control.InnerHtml = separator;
			
			return control;
		}
       #endregion Methods
   }
}
